package com.yuzhenxin.bookstore.dao;

import com.yuzhenxin.bookstore.domain.Book;
import com.yuzhenxin.bookstore.tools.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class BookDao {

    private final QueryRunner qr = new TxQueryRunner();

    /**
     * 查询所有图书
     */
    public List<Book> findAll() {
        try {
            String sql = "SELECT * FROM book";
            return qr.query(sql, new BeanListHandler<>(Book.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 按分类查询
     */
    public List<Book> findByCategory(String cid) {
        try {
            String sql = "SELECT * FROM book where cid=?";
            return qr.query(sql, new BeanListHandler<>(Book.class), cid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加载方法
     */
    public Book findByBid(String bid) {
        try {
            String sql = "SELECT * FROM book where bid=?";
            return qr.query(sql, new BeanHandler<>(Book.class), bid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
